﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using publicLibrary;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver.Builders;
using MongoDB.Bson.Serialization;

namespace asMeishi.web.Models
{
    public class food : MongoDocument
    {
        /// <summary>
        /// 菜名
        /// </summary>
        [BsonElement("N")]
        public string name { get; set; }
        /// <summary>
        /// 价格
        /// </summary>
        [BsonElement("P")]
        public double price { get; set; }
        /// <summary>
        /// 介绍
        /// </summary>
        [BsonElement("I")]
        public string intro { get; set; }
        /// <summary>
        /// 属于哪家商户
        /// </summary>
        [BsonElement("SI")]
        public ObjectId shopId { get; set; }
        /// <summary>
        /// 菜属性，辣:1,2,3级，甜,1,2,3，咸，
        /// </summary>
        [BsonElement("A")]
        public Dictionary<string, string> attribute { get; set; }
        /// <summary>
        /// 标签
        /// </summary>
        [BsonElement("T")]
        public List<string> tags { get; set; }
        /// <summary>
        /// 图片的文件名组
        /// </summary>
        [BsonElement("PS")]
        public List<string> picUrls { get; set; }
        /// <summary>
        /// 赞美(推荐)次数 
        /// </summary>
        [BsonElement("RC")]
        public int recommendCount { get; set; }
        /// <summary>
        /// 反对(差评)次数
        /// </summary>
        [BsonElement("OC")]
        public int opposeCounnt { get; set; }
        /// <summary>
        /// 印象评分 (0为未评价，1....5);
        /// </summary>
        [BsonElement("G")]
        public double grade { get; set; }
        /// <summary>
        /// 印象评分次数
        /// </summary>
        [BsonElement("GC")]
        public double gradeCount { get; set; }
        /// <summary>
        /// 平均分 
        /// </summary>
        [BsonElement("AG")]
        public double average_grade { get; set; }
        /// <summary>
        /// 回复次数 
        /// </summary>
        [BsonElement("CC")]
        public int commentsCount { get; set; }
        ///// <summary>
        ///// 创建的用户id
        ///// </summary>
        //public ObjectId userId { get; set; }
        ///// <summary>
        ///// 创建的用户name
        ///// </summary>
        //public string userName { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        [BsonElement("D")]
        public DateTime datatime { get; set; }
        /// <summary>
        /// 最后使用时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        [BsonElement("LD")]
        public DateTime lastDatatime { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string bak { get; set; }
        /// <summary>
        /// 0:未发布，1：发布
        /// </summary>
        [BsonDefaultValue(1)]
        public int release { get; set; }
        /// <summary>
        /// 评价印象,放在单独表中x
        /// </summary>
        //public List<impress> comments { get; set; }

    }

    public class foodC 
    {
        public DataSession<MongoDataContext, food> db = new DataSession<MongoDataContext, food>();


        /// <summary>
        /// 创建
        /// </summary>
        /// <returns></returns>
        public food createDefault()
        {
            var item = new food();
            item.datatime = DateTime.Now;
            item.lastDatatime = DateTime.Now;
            //item.userId = userC.loginUser.Id;
            item.shopId = new shopC().getTestId();
            item.recommendCount = 0;
            return item;
        }

        /// <summary>
        /// 为店加菜
        /// </summary>
        /// <param name="names"></param>
        /// <param name="shopId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<food> add(string[] names, ObjectId shopId, user user,int release=1)
        {
            List<food> items = new List<food>();
            for (var i = 0; i < names.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(names[i]))
                {
                    items.Add(null);
                }
                else
                {
                    items.Add(add(names[i], shopId, user, release));
                }
            }
            return items;
        }
        /// <summary>
        /// 为店加菜，并通过shopId补完food记录
        /// </summary>
        /// <param name="names"></param>
        /// <param name="shopId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IEnumerable<food> add(IEnumerable<food> foods,ObjectId shopId,user user)
        {
            if (foods == null) return null;

            var _foods = db.Where(d=>d.shopId== shopId);
            food _food;
            foreach(var f in foods){
                _food = _foods.FirstOrDefault(d=>d.name == f.name);
                if (_food != null)
                {
                    _food.shopId = shopId;
                    _food.recommendCount++;
                    db.Save(_food);
                }
                else {
                    db.Add(f);
                    
                }

                
            }
            _foods = db.Where(d => d.shopId == shopId);
            return _foods;
        }
        /// <summary>
        /// 对于item表中增加不存在的新菜可增加，根据shopId和str中的name，并返回shopId的全部item记录
        /// </summary>
        /// <param name="str"></param>
        /// <param name="shopId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>

        public List<food> addstr(string str, ObjectId shopId, user user)
        {
            string[] nameArr = str.trySplit(",").ToList().ToArray();
            for (var i = 0; i < nameArr.Length; i++)
            {
                add(nameArr[i], shopId, user);
            }
            return db.Where(d=>d.shopId==shopId).ToList();

        }

        /// <summary>
        /// 将来之前端json串的foods信息转为list<food>，并把shopID和user信息写入
        //  food格式[{food:{name:\"xxxx\"},impress:{content:\"mmm[xxaasd-1]mmm\"}},{food:{name:\"xxxx\"},impress:{content:\"mmmmmm\"}}]
        /// </summary>
        /// <param name="str"></param>
        /// <param name="shopId"></param>
        /// <param name="user"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        //public static Dictionary<food,impress> jsonStrToDictFoods(string str, ObjectId shopId, DateTime datetime)
        //{

        //    System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        //    var xx = jss.Deserialize<Dictionary<food, impress>>(str);
        //    if (xx == null) return null;
        //    foreach (var f in xx)
        //    {
        //        (food)f.Key. = shopId;
        //        f.datatime = f.lastDatatime = datetime;
        //    }
        //    return xx;
        //}
        /// <summary>
        /// 添加菜：判断是否存在，无则加入新的，有则计数加1
        /// </summary>
        /// <param name="name"></param>
        /// <param name="shopId"></param>
        /// <param name="userId"></param>
        public food add(string name, ObjectId shopId, user user, int release=1)
        {

            food item = getByName_ShopId(name, shopId);
            if (item == null)
            {
                item = createDefault();
                item.release = release;
                item.name = name;
                item.lastDatatime = DateTime.Now;
                item.shopId = shopId;
                item.recommendCount = 1;
            }
            else
            {
                item.lastDatatime = DateTime.Now;
                item.shopId = shopId;
                item.recommendCount++;
            }
            db.Save(item);
            //加入历史
            historyC<food>.Add(item.Id, item.name, historyTypeEnum.建立, "", user);
            return item;
        }
        public food getByShopAndName(ObjectId id,string name)
        {
            var q1 = Query.EQ(BsonClassMap.LookupClassMap(typeof(food)).GetMemberMap("shopId").ElementName, id);
            var q2 = Query.EQ(BsonClassMap.LookupClassMap(typeof(food)).GetMemberMap("name").ElementName, name);
            var q = Query.And(new IMongoQuery[] { q1,  q2});
            return db.Mquery.FindOne(q);

        }
        public food getById(string id)
        {
            return db.GetById(id);
        }
        /// <summary>
        /// 取得impress
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<impression> getImpress(string foodId,int start =0 ,int end = 0)
        {
            DataSession<MongoDataContext, impression> db2 = new DataSession<MongoDataContext, impression>();

            var data = db2.Where(d => d.targetId == ObjectId.Parse(foodId)).OrderByDescending(d => d.datetime).ToList();
            if (data == null) return data = new List<impression>();
                return data;

        }
        /// <summary>
        /// 写入impress
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public impression addImpress(ref food item, string content,int grade, user user)
        {
            item.commentsCount++;
            impressionC<food> fc = new impressionC<food>();
            var imp = fc.create(item.Id, user);
            imp.content = content;
            if (grade > 0)//有评分时
            {
                imp.grade = grade;
                item.grade += grade;
                item.gradeCount++;
                item.average_grade = item.grade / item.gradeCount;

                if (grade >3)
                {
                    item.recommendCount++;
                }
                else if(grade<3){
                    item.opposeCounnt++;
                }
                //更新时间
                item.lastDatatime = DateTime.Now;
                db.Save(item);
            }

        
            DataSession<MongoDataContext, impression> impDb = new DataSession<MongoDataContext, impression>();

            impDb.Save(imp);

            

            return imp;
        }
        public bool delImpress(food item, string impressId,user user)
        {
            DataSession<MongoDataContext, impression> impDb = new DataSession<MongoDataContext, impression>();

                //问题:给个impressId 结果所有的impress全被删
                impDb.Delete(impressId);

            item.commentsCount--;
            db.Save(item);
            
            return true;
        }
        /// <summary>
        /// get
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public IQueryable<food> getsByShopId(ObjectId shopId)
        {
            return db.Where(d => d.shopId == shopId);
            //return db.find(d => d.shopId == shopId);
        }

        private food getByName_ShopId(string name, ObjectId shopId)
        {
            return db.Get(d => d.shopId == shopId && d.name == name);
        }

        public void del(string id)
        {

        }

        public void delByShopId(string shopId)
        {

        }
        public void save(food item)
        {
            db.Save(item);
        }
        /// <summary>
        /// 添加图片，不保存
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public string addPic(ref food food, HttpPostedFileBase file)
        {

            myUpload upload = new myUpload();
            upload.myDirectory = "foodPic";
            upload.imageResize = "640*480";

            try
            {
                string fileName = upload.imageSave(file, true);
                //加到picUrlList字段中
                if (food.picUrls == null) food.picUrls = new List<string>();
                food.picUrls.Add(fileName);
                return fileName;

            }
            catch (Exception ex)
            {
                return null;
                //throw new asMeishiException("fuck" + ex.Message);
            };

            //upload.Dispose();
            //return shop;
        }
        /// <summary>
        /// 增加图片。但不保存
        /// </summary>
        /// <param name="shop"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public food addPic(food food, HttpPostedFileBase file)
        {

            myUpload upload = new myUpload();
            upload.myDirectory = "foodPic";
            upload.imageResize = "640*480";
            try
            {
                string fileName = upload.imageSave(file, true);
                //加到picUrlList字段中
                if (food.picUrls == null) food.picUrls = new List<string>();
                food.picUrls.Add(fileName);
                db.Save(food);

            }
            catch (Exception ex)
            {
                //throw new asMeishiException("fuck" + ex.Message);
            };

            //upload.Dispose();

            return food;
        }
        //删除图片,不存保
        public bool delPic(ref food food, string picUrl)
        {
            try
            {


                food.picUrls.Remove(picUrl);
                myUpload.delImage("shopPic" + picUrl);
                return true;
            }
            catch
            {
                return false;
            }

        }

    }

}